﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using NTwitter;
using System.Collections.ObjectModel;
using System.Net;
using System.IO;
using System.Windows.Forms;


namespace TwitterClient2.Model
{
    class TwitterClientModel
    {

        public String username { get; set; }
        public String password { get; set; }
        public Collection<User> followers { get; set; }
        public Collection<User> friends { get; set; }
        public Collection<Status> myTweets { get; set; }
        public Collection<Message> messages { get; set; }
        public Collection<Message> messagesSent { get; set; }
        public Collection<Status> publicTweets { get; set; }
        public Collection<Status> friendsTweets { get; set; }
        public Collection<Status> userTweets { get; set; }
        public Collection<Status> mentionTweets { get; set; }
        private NTwitter.Twitter twitter;
        private static TwitterClientModel model = null;


        private TwitterClientModel()
        {

        }

        public bool authentification(String username, String password, out String message)
        {
            this.username = username;
            this.password = password;
            message = "";
            this.twitter = new NTwitter.Twitter(username, password);
            try
            {
                this.followers = this.getFollowers();
                this.friends = this.getFriends();
                this.myTweets = this.getMyTweets();
                this.messages = this.getReceivedDirectMessages();
                this.messagesSent = this.getSentDirectMessages();
                this.publicTweets = this.getPublicTweets();
                this.friendsTweets = this.getFriendsTweets();
                this.userTweets = this.getMyTweets();
                this.mentionTweets = this.getMentionTweets();

            }
            catch (TwitterException t)
            {
                WebException webEx = t.InnerException as WebException;


                if (webEx.Response != null)
                {
                    HttpStatusCode code = ((HttpWebResponse)webEx.Response).StatusCode;
                    if (code == HttpStatusCode.Unauthorized)
                        message = "Username and/or Password are not valid!";
                    else
                        message = "Following Exception: " + code.ToString();

                }
                else
                    message = "There is a problem with your internet connection. Please check your properties";
                return false;
            }
            return true;
        }

        public void updateStatus(String text)
        {
            this.twitter.UpdateStatus(text);

        }

        //public void UpdateStatusInReplyToStatusId(String text, String username, long id)
        //{
        //    this.twitter.UpdateStatusInReplyToStatusId(text, username, id);
        //}

        public void UpdateStatusInReplyToUser(String text, String username)
        {
            this.twitter.UpdateStatus("@" + username + " " + text);
        }

        public void destroyStatus(long id)
        {
            this.twitter.DestroyStatus(id);
        }

        public void test()
        {
            //this.twitter.Search("Moin");
        }

        public User getUser(String username)
        {
            return this.twitter.Show(username);

        }

        public bool exitsUser(String username)
        {
            return this.twitter.UserExists(username);
        }

        public void stopFollowing(String username)
        {
            this.twitter.StopFollowing(username);
        }

        public void follow(String username)
        {
            this.twitter.Follow(username);
        }

        public void sendDirectMessage(String receiver, String message)
        {
            this.twitter.SendMessage(receiver, message);
        }

        public Collection<Message> getReceivedDirectMessages()
        {
            return this.twitter.GetDirectMessages();
        }

        public Collection<Message> getSentDirectMessages()
        {
            return this.twitter.GetDirectMessagesSent();
        }

        public Collection<User> getFollowers()
        {
            return this.twitter.GetFollowers();
        }

        public Collection<User> getFriends()
        {

            Collection<User> users = new Collection<User>();
            foreach (long l in this.twitter.GetFriendIds())
            {
                users.Add(this.twitter.Show(l + ""));
            }
            return users;
        }
        public Collection<Status> getMyTweets()
        {
            return this.twitter.GetUserTimeline();
        }

        public Collection<Status> getPublicTweets()
        {
            return this.twitter.GetPublicTimeline();
        }

        public Collection<Status> getFriendsTweets()
        {
            return this.twitter.GetFriendsTimeline();
        }

        public Collection<Status> getMentionTweets()
        {
            return this.twitter.getMentionTimeline();
        }

        public Collection<Status> search(string searchText)
        {
            return this.twitter.Search(searchText, 1);
        }

        public Collection<Status> searchFromUser(string seachText)
        {
            return this.twitter.Search(seachText, 2);
        }

        public Collection<Status> searchReplyToUser(string seachText)
        {
            return this.twitter.Search(seachText, 3);
        }
        public static TwitterClientModel getInstance()
        {
            if (model == null)
            {
                model = new TwitterClientModel();
            }
            return model;
        }

        public byte[] downLoadData(String url)
        {



            byte[] downloadedData = new byte[0];
            try
            {

                //Get a data stream from the url
                WebRequest req = WebRequest.Create(url);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                //Download in chuncks
                byte[] buffer = new byte[1024];

                //Get Total Size
                int dataLength = (int)response.ContentLength;





                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                while (true)
                {
                    //Try to read the data
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                        break;
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);
                    }
                }

                //Convert the downloaded stream to a byte array
                downloadedData = memStream.ToArray();

                //Clean up
                stream.Close();
                memStream.Close();

            }
            catch (Exception)
            {
                MessageBox.Show("Cannot download Image");
            }
            return downloadedData;
        }

        internal void updateData()
        {
            this.followers = this.getFollowers();
            this.friends = this.getFriends();
            this.myTweets = this.getMyTweets();
            this.messages = this.getReceivedDirectMessages();
            this.messagesSent = this.getSentDirectMessages();
            this.publicTweets = this.getPublicTweets();
            this.friendsTweets = this.getFriendsTweets();
            this.userTweets = this.getMyTweets();
            this.mentionTweets = this.getMentionTweets();

        }

        public void addFriend(String user)
        {
            this.twitter.Follow(user);
            this.friends = this.getFriends();
        }

        public void removeFriend(String user)
        {
            this.twitter.StopFollowing(user);
            this.friends = this.getFriends();
        }
    }
}
